package org.jkuang.qstar.commons.io;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileWriter  

{

	BufferedOutputStream out;

	byte[] temp = new byte[8];

	public FileWriter(String file) throws FileNotFoundException {
		this.out = new BufferedOutputStream(new FileOutputStream(file),1024*4);
	}
	public FileWriter(File file,boolean append) throws FileNotFoundException {
		this.out = new BufferedOutputStream(new FileOutputStream(file,append),1024*4);
	}
	public void writeByte(byte v) throws IOException {
		this.out.write(v);
	}

	public void writeShort(short v) throws IOException {
		this.out.write((byte) (v >>> 8));
		this.out.write((byte) v);
	}

	public void writeInt(int v) throws IOException {
		this.out.write((byte) (v >>> 24));
		this.out.write((byte) (v >>> 16));
		this.out.write((byte) (v >>> 8));
		this.out.write((byte) v);
	}

	public void writeLong(long v) throws IOException {
		this.writeInt((int) (v >>> 32));
		this.writeInt((int) v);
	}

	public void writeBytes(byte[] bs) throws IOException {
		this.out.write(bs);
	}

	public void writeShortBytes(byte[] bs) throws IOException {
		if (bs == null || bs.length == 0) {
			this.writeShort((short) 0);
		} else {
			this.writeShort((short) bs.length);
			if (bs.length > Short.MAX_VALUE) {
				this.out.write(bs, 0, Short.MAX_VALUE);
			} else {

				this.out.write(bs);
			}
		}
	}

	public void writeIntBytes(byte[] bs) throws IOException {
		if (bs == null || bs.length == 0) {
			this.writeInt(0);
		} else {
			this.writeInt(bs.length);
			this.out.write(bs);
		}
	}

	public void flush() throws IOException {
		this.out.flush();
	}

	public void close() {

		try {
			this.flush();
			this.out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
